<template>
  <!-- <div v-if="isShow" class="app-container home"> -->
    <div  class="app-container home">
    <div class="Knowledge_volume">
      <h2>知识量统计</h2>
      <div class="model" v-loading="loadingStatistic">
        <div
          class="sbu_module"
          v-for="(item, index) in statisticList"
          :key="index"
          @click="toDetailList(item)"
        >
          <i class="icon iconfont el-icon-s-management"></i>
          <p>
            <span>{{ item.fileType }}</span>
            <span>{{ !isNaN(item.number) ? item.number : "**" }}条</span>
          </p>
        </div>
      </div>
    </div>
    <div class="recommendation">
      <h2>知识推荐</h2>
      <div class="knowledgeList" :style="leftClientHeight">
        <div
          v-for="(item, index) in tableData"
          :key="index"
          class="knowledgeList_item"
        >
          <div
            class="number"
            :style="
              index === 0
                ? 'color: #F53F3F'
                : index === 1
                ? 'color: #FAAD14'
                : ''
            "
          >
            {{ index + 1 }}
          </div>
          <div class="info">
            <div class="info_title">{{ item.fileName }}</div>
            <!-- <div class="info_content knowledge">
                相关知识：{{ item.ext.items[0].text }}
              </div> -->
            <div class="info_content">
              <div>上传日期：{{ item.uploadTime }}</div>
              <div style="margin-left: 20px">总收藏数{{ item.collectNumber }}</div>
              <div class="info_content_label">
                {{ item.professionName }}
              </div>
            </div>
          </div>
          <div class="collect">
            <img
              @click.stop="collectionFn(item)"
              class="nomore"
              :src="
                item.collect == 1
                  ? require('@/assets/images/collect_yes.png')
                  : require('@/assets/images/collect_no.png')
              "
              style="width: 22px; height: 22px"
            />
            <div>
              <el-button type="primary" @click="viewFn(item)" size="small"
                >查看详情</el-button
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="recommendation">
      <h2>热门工艺知识</h2>
      <div class="knowledgeList" :style="leftClientHeight">
        <div
          v-for="(item, index) in hotCarftData"
          :key="index"
          class="knowledgeList_item"
        >
          <div
            class="number"
            :style="
              index === 0
                ? 'color: #F53F3F'
                : index === 1
                ? 'color: #FAAD14'
                : ''
            "
          >
            {{ index + 1 }}
          </div>
          <div class="info">
            <div class="info_title">{{ item.fileName }}</div>
            <!-- <div class="info_content knowledge">
                相关知识：{{ item.ext.items[0].text }}
              </div> -->
            <div class="info_content">
              <div>上传日期：{{ item.updateTime }}</div>
              <div style="margin-left: 20px">总收藏数{{ item.collectNumber }}</div>
              <div class="info_content_label">
                {{ item.professionName }}
              </div>
            </div>
          </div>
          <div class="collect">
            <img
              @click.stop="collectionFn(item)"
              class="nomore"
              :src="
                item.collect == 1
                  ? require('@/assets/images/collect_yes.png')
                  : require('@/assets/images/collect_no.png')
              "
              style="width: 22px; height: 22px"
            />
            <div>
              <el-button type="primary" @click="viewFn(item)" size="small">查看详情</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 预览 -->
    <el-dialog
      class="fullscreen_preview"
      :visible.sync="previewVisible"
      fullscreen
      :close-on-click-modal="false"
      center
    >
      <div slot="title" class="header_button">
        <img class="icon" @click="changeLike"
             :src="addForm.like==1?require('../assets/images/heart_fill.png'):require('../assets/images/heart.png')"/>
        <span>{{ addForm.likeNumber || '' }}</span>
        <img class="icon" @click="changeCollect()"
             :src="addForm.collect == 1?require('../assets/images/collect_yes.png'):require('../assets/images/collect_no.png')"/>
        <span>{{ addForm.collectNumber || '' }}</span>
      </div>
      <iframe
        v-loading="previewLoading"
        id="iframe"
        src=""
        frameborder="0"
        width="100%"
        height="100%"
      ></iframe>
    </el-dialog>

    <!-- 预览视频 -->
    <el-dialog
      class="fullscreen_preview"
      :visible.sync="videoVideoVisible"
      :close-on-click-modal="false"
      fullscreen
      center
    >
      <div slot="title" class="header_button">
        <img class="icon" @click="changeLike"
             :src="addForm.like==1?require('../assets/images/heart_fill.png'):require('../assets/images/heart.png')"/>
        <span>{{ addForm.likeNumber || '' }}</span>
        <img class="icon" @click="changeCollect()"
             :src="addForm.collect == 1?require('../assets/images/collect_yes.png'):require('../assets/images/collect_no.png')"/>
        <span>{{ addForm.collectNumber || '' }}</span>
      </div>
      <div class="video_model">
        <div id="video"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Index",
  data() {
    return {
      pageNo: 1,
      pageSize: 10,
      total: 100,
      loadingRecommend: false,
      loadingStatistic: false,
      previewVisible: false,
      previewLoading: false,
      videoVideoVisible: false,
      tableData: [],
      statisticList: [],
      hotCarftData: [],
      isShow: false,
      //pdf、视频预览
      addForm: {
        like: 0,
        collect: 0,
        likeNumber: 0,
        collectNumber: 0,
        selected: false
      },
      collectLikeId: '',
    };
  },
  computed: {
    leftClientHeight() {
      let tableClientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      tableClientHeight = tableClientHeight - 329;
      return { height: tableClientHeight + "px" };
    },
    tableClientHeight() {
      let tableClientHeight =
        document.documentElement.clientHeight || document.body.clientHeight;
      tableClientHeight = tableClientHeight - 509;
      return tableClientHeight;
    },
  },
  mounted() {
    this.getRecommendList();
    this.getStatisticList();
    this.hotCarftDataFn();
    // 判断是否有权限访问首页
    const result = JSON.parse(localStorage.getItem("router"));
    if (!result) return;
    console.log(
      "66",
      result.find((item) => item.route == "/")
    );
    // this.isShow = result.find((item) => item.route == "/") ? true : false;
  },
  methods: {
    //pdf、视频预览
    changeLike() {
      let url = this.addForm.like==1 ? '/knowledgeCollect/delete' : '/knowledgeCollect/add'
      this.$http({
        url: url,
        method: 'post',
        data: {
          collectType: 1,
          knowledgeFileId: this.collectLikeId
        }
      }).then(({data}) => {
        if (data.code == 200) {
          this.$message.success(this.addForm.like==1?'取消点赞成功':'点赞成功')
          this.getCollectLike()
        }
      })
    },
    changeCollect() {
      let url = this.addForm.collect==1 ? '/knowledgeCollect/delete' : '/knowledgeCollect/add'
      this.$http({
        url: url,
        method: 'post',
        data: {
          collectType: 2,
          knowledgeFileId: this.collectLikeId
        }
      }).then(({data}) => {
        console.log(data, 'llll')
        if (data.code == 200) {
          this.$message.success(this.addForm.collect==1?'取消收藏成功':'收藏成功')
          this.getCollectLike()
          // 找到对应项并更新
          const item = this.tableData.find(item => item.id === this.collectLikeId) || this.hotCarftData.find(item => item.id === this.collectLikeId);
          if (item) {
            this.updateCollectStatus(item, this.addForm.collect == 1 ? 0 : 1, this.addForm.collect == 1 ? -1 : 1);
          }
        }
      })
    },
    getCollectLike() {
      this.$http({
        url: '/knowledgeData/addView',
        method: 'post',
        data: {
          id: this.collectLikeId,
        }
      }).then(({data}) => {
          this.addForm = data.data
      });
    },
    updateCollectStatus(item, collectStatus, collectNumberChange) {
      // 确保 collectNumber 不小于 0
      const newCollectNumber = Math.max(0, item.collectNumber + collectNumberChange);
      this.$set(item, 'collect', collectStatus);
      this.$set(item, 'collectNumber', newCollectNumber);

      // 更新 tableData 和 hotCarftData 中的对应项
      const tableIndex = this.tableData.findIndex(dataItem => dataItem.id === item.id);
      if (tableIndex !== -1) {
        this.$set(this.tableData, tableIndex, { ...this.tableData[tableIndex], collect: collectStatus, collectNumber: item.collectNumber });
      }

      const hotCarftIndex = this.hotCarftData.findIndex(dataItem => dataItem.id === item.id);
      if (hotCarftIndex !== -1) {
        this.$set(this.hotCarftData, hotCarftIndex, { ...this.hotCarftData[hotCarftIndex], collect: collectStatus, collectNumber: item.collectNumber });
      }
    },

    viewFn(row) {
      let that = this;
      console.log(row, "55555");
      // if (row.fileType == "video") {
      //   this.videoVideoVisible = true;
      //   this.$http({
      //     url: "/knowledgeData/preview",
      //     method: "get",
      //     params: {
      //       id: row.id,
      //     },
      //   }).then(({ data }) => {

      //     console.log("获取文件之后地址", data.data.downloadUrl);

      //   });
      // }
      this.collectLikeId = row.id;
      this.getCollectLike()
      this.$http({
        url: "/knowledgeData/release/preview",
        method: "get",
        params: {
          id: row.id,
        },
      }).then(({ data }) => {
        if (data.code == 1000) {
          this.$message.warning(data.msg);
          return;
        }
        if (data.readAuthority == false) {
          this.$message.warning("当前文件不可预览");
          return;
        }
        if (row.fileType == "video") {
          this.videoVideoVisible = true;
          setTimeout(() => {
            new this.$Player({
              id: "video", // 元素id
              lang: "zh", // 设置中文
              volume: 0, // 默认静音
              autoplay: false, // 自动播放
              screenShot: false, // 开启截图功能
              height: 200,
              // 视频地址
              url: this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl,
              // 封面图
              // poster:'',
              fluid: true, // 填满屏幕 （流式布局）
              playbackRate: [0.5, 0.75, 1, 1.5, 2], // 传入倍速可选数组
            });
          }, 300);
          return;
        }
        this.previewVisible = true;
        setTimeout(() => {
          var iframe = document.querySelector("#iframe");
          this.populateIframe(
            iframe,
            [["token", +localStorage.getItem("token")]],
            this.$config.VUE_APP_BASE_API_QA + data.data.downloadUrl
          );
        }, 0);
      });
    },
    hotCarftDataFn() {
      this.$http({
        url: "/knowledgeSearch/hotKnowledge",
        method: "get",
        params: {},
      }).then(({ data }) => {
        console.log(data);
        this.hotCarftData = data.data;
      });
    },
    toDetailList(item) {
      //进入查看页面
      // return
      console.log(item);
      this.$router.push({
        path: "viewList",
        query: {
          fileType: item.id,
        },
      });
    },
    populateIframe(iframe, headers, url) {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.responseType = "blob";
      headers.forEach((header) => {
        xhr.setRequestHeader(header[0], header[1]);
      });
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key-MD5", "m7AXuOLSaEQc1369IHCZGw==")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Algorithm", "AES256")
      // xhr.setRequestHeader("X-Amz-Server-Side-Encryption-Customer-Key", "5svVq6aMjTLMBTD0yaIT9u735QnpHteabx6nFZUXvac=")
      xhr.onreadystatechange = () => {
        if (xhr.readyState === xhr.DONE) {
          if (xhr.status === 200) {
            console.log(URL.createObjectURL(xhr.response), "ffff");
            this.previewUrl = URL.createObjectURL(xhr.response);
            console.log("预览地址", URL.createObjectURL(xhr.response));
            iframe.src =
              "./static/pdfjs/web/viewer.html?file=" +
              URL.createObjectURL(xhr.response);
          }
        }
      };
      xhr.send();
    },
    sizeChangeHandle(val) {
      this.pageSize = val;
      this.pageNo = 1;
      this.getRecommendList();
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageNo = val;
      this.getRecommendList();
    },
    getRecommendList() {
      this.loadingRecommend = true;
      this.$http({
        url: "/front/recommend",
        method: "GET",
        params: {},
      }).then(({ data }) => {
        this.tableData = data.data;
        this.loadingRecommend = false;
      });
    },
    getStatisticList() {
      this.loadingStatistic = true;
      this.$http({
        url: "/front/statistic",
        method: "GET",
        params: {},
      }).then(({ data }) => {
        this.statisticList = data.data;
        this.loadingStatistic = false;
      });
    },
    collectionFn(item) {
      console.log(item,'收藏')
        this.$http({
          url:
            item.collect == 1
              ? "/knowledgeCollect/delete"
              : "/knowledgeCollect/add",
          method: "post",
          data: {
            collectType: 2,
            knowledgeFileId: item.id,
          },
        }).then(({ data }) => {
          if (data.code == 200) {
            if (item.collect == 1) {
              this.$message.success("取消收藏成功");
              // item.collect = 0;
              // item.collectNumber -- 
              this.updateCollectStatus(item, 0, -1);

            } else {
              this.$message.success("收藏成功");
              // item.collect = 1;
              // item.collectNumber ++
              this.updateCollectStatus(item, 1, 1);

            }
          }
        });
    },
    quitCollectionFn(item) {
      this.$http({
        url: "/knowledgeCollect/delete",
        method: "post",
        data: {
          collectType: 2,
          knowledgeFileId: item.id,
        },
      }).then(({ data }) => {
        if (data.code == 200) {
          this.$message.success("取消收藏成功");
          item.collect = 0;
        }
      });
    },
  },
};
</script>

<style scoped lang="scss">
.home {
  .recommendation {
    width: 100%;
    background: white;
    border-radius: 10px;
    padding: 20px;
    margin-top: 40px;
    margin-bottom: 40px;
    // min-height: 55vh;

    h2 {
      color: #101010;
      font-size: 23px;
      margin-top: 0px;
      font-weight: 600;
    }
  }

  .Knowledge_volume {
    width: 100%;
    background: white;
    border-radius: 10px;
    padding: 20px;
    margin-top: 20px;
    cursor: pointer;

    h2 {
      color: #101010;
      font-size: 23px;
      font-weight: 500;
      margin-top: 0px;
    }

    .model {
      width: 100%;
      height: 130px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      overflow-x: hidden;
      gap: 20px;

      .sbu_module {
        height: 100px;
        color: white;
        padding: 10px 20px;
        border-radius: 5px;
        display: flex;
        flex-direction: row;
        // justify-content: center;
        align-items: center;
        transition: transform 0.3s ease;
        box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
        width: 20%;

        &:hover {
          transform: scale(1.1);
        }

        .icon {
          font-size: 45px;
        }

        p {
          display: flex;
          flex-direction: column;
          margin-left: 10px;

          span:nth-child(1) {
            font-weight: bold;
          }
          span:nth-child(2) {
            font-size: 20px;
            font-weight: normal;
          }
        }
      }

      div:nth-child(1) {
        background: #ff7970;
      }

      div:nth-child(2) {
        background: #ffd344;
      }

      div:nth-child(3) {
        background: #648cff;
      }

      div:nth-child(4) {
        background: #4fccb0;
      }

      div:nth-child(5) {
        background: #764fcc;
      }

      div:nth-child(6) {
        background: #0052d9;
      }
      div:nth-child(7) {
        background: #344258;
      }
      div:nth-child(8) {
        background: #d72d9e;
      }
      div:nth-child(9) {
        background: #23dc86;
      }
    }
  }
}

.video_model {
  // width: 260px;
  // height: 190px;
  width: 100%;
  // height: 85vh !important;
  // background: red;
  // border: 1px solid #e6e6e6;
  border-radius: 5px;
  margin-bottom: 20px;

  #video {
    flex: auto;
    height: 85vh !important;
  }

  .video_info {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    padding: 10px;
    line-height: 22px;

    h3 {
      flex: 1;
      padding: 0;
      margin: 0;
      font-weight: 550;
      font-size: 18x;
    }

    .author,
    .blurb {
      font-size: 14px;
    }
  }
}

.knowledgeList {
  overflow-y: auto;
  .knowledgeList_item {
    margin-bottom: 10px;
    background: #f9fbfc;
    border: 1px dashed #dcdee1;
    display: flex;
    justify-content: space-between;
    padding: 10px;
    .number {
      width: 40px;
    }
    .info {
      width: 90%;
      .info_title {
        font-size: 18px;
      }
      .info_content.knowledge {
        //height: 120px;
        overflow: hidden;
        text-overflow: ellipsis;
        width: 99%;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        text-align: justify;
      }
      .info_content {
        margin-top: 5px;
        font-size: 12px;
        display: flex;
        align-items: center;
        color: #4c5a67;
        .info_content_label {
          border-radius: 16px;
          background: #0084ff;
          color: #fff;
          padding: 2px 10px;
          margin-left: 20px;
        }
      }
    }
    .collect {
      text-align: center;
      .nomore{
        cursor: pointer;
      }
    }
  }
}
</style>
